import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';



import Login from '@/components/login/login.vue'   //登录页
import Home from '@/components/home/home.vue'    //首页
import emptyPage from '@/components/emptyPage/emptyPage.vue'    //空页面


// 物联卡页面
//iot首页
import iotCard from '@/components/iotCard/iotHome/iotCardHome.vue'
import iotHome from '@/components/iotCard/iotHome/homeContent.vue'
//渠道列表
import channelList from '@/components/iotCard/channel/channelList.vue'
//订单管理
import commissio from '@/components/iotCard/order/commissio.vue'
import ordersList from '@/components/iotCard/order/ordersList.vue'
import orderDetail from '@/components/iotCard/order/orderDetail.vue'
import refund from '@/components/iotCard/order/refund.vue'
//财务管理
import bill from '@/components/iotCard/financia/bill.vue'
import outAccounting from '@/components/iotCard/financia/outAccounting.vue'
//套餐管理
import addCombo from '@/components/iotCard/combo/addCombo.vue'
import comboGroup from '@/components/iotCard/combo/comboGroup.vue'
import addComboGroup from '@/components/iotCard/combo/addComboGroup.vue' //添加套餐组
import comboGroupDetail from '@/components/iotCard/combo/comboGroupDetail.vue' //套餐组详情
import comboDetail from '@/components/iotCard/combo/comboListDetail.vue'
import comboAllocation from '@/components/iotCard/combo/comboAllocation.vue'
import comboList from '@/components/iotCard/combo/comboList.vue'
import poolList from "@/components/iotCard/combo/poolList";
//卡片管理
import cardList from '@/components/iotCard/card/cardList.vue'
import cardTask from '@/components/iotCard/card/cardTask.vue'
import newTask from '@/components/iotCard/card/newTask.vue'
import taskDetail from '@/components/iotCard/card/taskDetail.vue'
// 账单
import billingIndex from '@/components/iotCard/billing_order/index'
import billingDetail from '@/components/iotCard/billing_order/detail'





// // 商户管理页面
//商户首页
import business from '@/components/business/businessHome/businessHome.vue'
//商户
import administratorList from '@/components/business/tenant/administratorList.vue'
import administratorDetail from '@/components/business/tenant/administratorDetail.vue'
// 商户设置
import settingIndex from '@/components/business/setting/index.vue'
//权限管理
import undetermined from '@/components/business/activity/undetermined.vue'
//任务
import automation from '@/components/business/taks/automation.vue'
import timedTask from '@/components/business/taks/timedTask.vue'

//应用
import appLits from '@/components/business/app/appLits.vue'
import templateMessage from '@/components/business/app/templateMessage.vue'
import addApp from '@/components/business/app/addApp'
//微信用户
import userList from '@/components/business/wechat/userList.vue'

//下载页面
import download from '@/components/download/download.vue'
import dosageList from "@/components/iotCard/combo/dosageList";

const routerFile = {
  emptyPage: emptyPage,
  iotCard: iotCard,
  iotHome: iotHome,
  channelList: channelList,
  commissio: commissio,
  ordersList: ordersList,
  orderDetail: orderDetail,
  refund: refund,
  bill: bill,
  outAccounting: outAccounting,
  addCombo: addCombo,
  comboGroup: comboGroup,
  addComboGroup: addComboGroup,
  comboGroupDetail: comboGroupDetail,
  comboDetail: comboDetail,
  comboAllocation: comboAllocation,
  comboList: comboList,
  cardList: cardList,
  cardTask: cardTask,
  newTask: newTask,
  taskDetail: taskDetail,
  business: business,
  administratorList: administratorList,
  administratorDetail: administratorDetail,
  undetermined: undetermined,
  automation: automation,
  timedTask: timedTask,
  appLits: appLits,
  templateMessage: templateMessage,
  addApp: addApp,
  userList: userList,
  download: download,
  "setting/index": settingIndex,
  "billing/index": billingIndex,
  "billing/detail": billingDetail,
  "pool/list": poolList,
  "dosage/list": dosageList,
}

const routes = [
  {
    path: '/login',
    component: Login,
    title: '登录'
  },
  {
    path: '/',
    redirect: '/home',
  },
  {
    path: '/businessHome',
    redirect: '/administratorList'
  },
  {
    path: '/emptyPage',
    component: emptyPage,
    name: '无权限页面'
  },
]

const router = new VueRouter({
  mode: 'history',
  routes
})
let one = []
router.setRouterPath = () => {
  let routerPower = []
  let routerData = JSON.parse(localStorage.getItem('userData')).menus

  let routerPath = {
    path: '/home',
    component: Home,
    meta: {
      title: '项目首页'
    },
    children: []
  }

  routerData.forEach((model, modelIndex) => {
    model.path = `/${model.route}`
    model.name = model.title
    model.meta = {}
    model.meta.title = model.title
    model.component = routerFile[model.route]
    model.redirect = `/${model.children[0].route}`

    model.children.forEach((menus, menusIndex) => {
      menus.path = `/${menus.route}`
      menus.name = menus.title
      menus.meta = {}
      menus.meta.title = menus.title
      if (routerFile[menus.route]) {
        menus.component = routerFile[menus.route]
      } else {
        menus.component = { render: (e) => e("router-view") }
      }

      if (menus.children.length > 0) {
        menus.redirect = `/${menus.children[0].route}`
      }

      if (menus.type == 3) {
        routerPower.push(menus)
      }

      for (let i = menus.children.length - 1; i >= 0; i--) {
        if (menus.children[i].type == 3) {
          routerPower.push(menus.children[i])
        }
        if (!menus.children[i].route) {
          menus.children.splice(i, 1)
        }
      }
      menus.children.forEach((button, buttpnIndex) => {
        if (button.type == 3) {
          routerPower.push(button)
        }
        let path = {
          name: button.title,
          component: routerFile[button.route],
          route: `${button.route}`,
          title: button.title
        }
        button.children.push(path)
        button.path = `/${button.route}`
        button.name = button.title
        button.meta = {}
        button.meta.title = button.title
        button.component = {
          render(c) { return c('router-view') }
        }
        button.children.forEach(item => {
          if (item.type == 3) {
            routerPower.push(item)
          }
          if (item.name == button.name) {
            item.name = ''
          } else {
            item.name = item.title
          }
          item.path = `/${item.route}`

          item.meta = {}
          item.meta.title = item.title
          item.component = routerFile[item.route]
        })
      })
    })
  })
  routerPath.children = routerData
  routerPath.redirect = routerData[0].path
  router.addRoute(routerPath)
  one = routerPath
  localStorage.setItem('routerPower', JSON.stringify(routerPower))
  localStorage.setItem("routerPath", JSON.stringify(routerPath))
}
const token = JSON.parse(localStorage.getItem('token'))
if (token) {
  router.setRouterPath()
}

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = JSON.parse(localStorage.getItem('token'))
  //   // to将要访问的路径
  //   // from从哪个路径跳转而来
  //   // next 放行到哪里

  //   // 除了login不需要路由守卫 其他页面都需要路由守卫 有token密令才能放行 没有则强制回到login页面
  if (to.path == '/login') {
    return next()
  }
  // 如果没有token密令就强制跳转到login
  if (!token) {
    if (to.path == '/home') {
      return next('/login')
    }
    return next('/login'), alert('请先登录')
  }

  // 判断用户token是否超过七天 604800000 为七天的毫秒数
  if (token.nowTime > (new Date).getTime() - 604800000) {
    if (to.path === '/emptyPage') {
      return next()
    }

    let judge = false
    one.children.forEach((model, modelIndex) => {
      if (to.path === model.path) {
        judge = true
      }
      model.children.forEach((menus, menusIndex) => {
        if (to.path === menus.path) {
          judge = true
        }
        menus.children.forEach((button, buttpnIndex) => {
          if (to.path === button.path) {
            judge = true
          }
          button.children.forEach((item, buttpnIndex) => {
            if (to.path === item.path) {
              judge = true
            }
          })
        })
      })

    })
    judge ? next() : next('/emptyPage')
    document.title = router.history.current.meta.title

  } else {
    let code = localStorage.getItem('code')
    localStorage.clear()
    localStorage.setItem('code', code)
    router.push({ path: `/login?code=${code}` })
    alert('登录过期,请重新登录!')
  }

})

export default router
